package com.bookcloud.java21.chapter8.使用同步方法86;

public class SynchronizedStatement {
  public static void main(String[] args) throws InterruptedException {
    Counter counter = new Counter();

    // 创建多个线程，共享同一个Counter实例
    Thread[] threads = new Thread[10];

    for (int i = 0; i < 5; i++) {
      threads[i] =
          new Thread(
              new Runnable() {
                @Override
                public void run() {
                  for (int j = 0; j < 1000; j++) {
                    counter.increment();
                  }
                }
              },
              "增加线程-" + i);
    }

    for (int i = 5; i < 10; i++) {
      threads[i] =
          new Thread(
              new Runnable() {
                @Override
                public void run() {
                  for (int j = 0; j < 1000; j++) {
                    counter.decrement();
                  }
                }
              },
              "减少线程-" + (i - 5));
    }

    // 启动所有线程
    for (Thread thread : threads) {
      thread.start();
    }

    // 等待所有线程结束
    for (Thread thread : threads) {
      thread.join();
    }

    System.out.println("最终计数器的值: " + counter.getCount()); // 应该是0
  }
}
